package cn.jdemo.juc.thread;


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * 三种方式
 * 直接继承Thread,重写run()方法;
 * 直接实现Runnable,然后作为参数传入Thread;
 * 直接声明FutureTask(间接实现Runnable()),然后作为参数传入Thread;
 *
 * @description
 * @date 2020/12/14
 */
public class Demo01 {

    /**
     * 输出如下:
     * cn.jdemo.juc.thread.Demo01.test1:Thread-0
     * cn.jdemo.juc.thread.Demo01.test3:Thread-2
     * cn.jdemo.juc.thread.Demo01.test2:Thread-1
     */
    public static void main(String[] args) {
        test1();
        test2();
        List list = test3();
    }

    public static List test3() {
        FutureTask<List> futureTask  = new FutureTask<List>(()->{
            List<String> list = new ArrayList<>();
            // 计算...
            String str = "hello";
            list.add(str);
            System.out.println("cn.jdemo.juc.thread.Demo01.test3:"+Thread.currentThread().getName());
            return list;
        });
        new Thread(futureTask).start();

        List list = null;
        try {
            list = futureTask.get(2000, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            System.out.println("超时:"+e.getMessage());
            e.printStackTrace();
        }
        return list;
    }

    public static void test2() {
        new Thread(()->{
            System.out.println("cn.jdemo.juc.thread.Demo01.test2:"+Thread.currentThread().getName());
        }).start();
    }

    public static void test1() {
        Temp temp = new Demo01().new Temp();
        temp.start();
    }
    class Temp extends Thread{
        @Override
        public void run() {
            System.out.println("cn.jdemo.juc.thread.Demo01.test1:"+Thread.currentThread().getName());
            super.run();
        }
    }
}
